package com.qifan.energy.util.oss;

import com.alibaba.sdk.android.oss.ClientConfiguration;
import com.alibaba.sdk.android.oss.ClientException;
import com.alibaba.sdk.android.oss.OSSClient;
import com.alibaba.sdk.android.oss.ServiceException;
import com.alibaba.sdk.android.oss.callback.OSSCompletedCallback;
import com.alibaba.sdk.android.oss.callback.OSSProgressCallback;
import com.alibaba.sdk.android.oss.common.OSSLog;
import com.alibaba.sdk.android.oss.common.auth.OSSCredentialProvider;
import com.alibaba.sdk.android.oss.common.auth.OSSStsTokenCredentialProvider;
import com.alibaba.sdk.android.oss.internal.OSSAsyncTask;
import com.alibaba.sdk.android.oss.model.PutObjectRequest;
import com.alibaba.sdk.android.oss.model.PutObjectResult;
import com.qifan.energy.global.Keys;
import com.qifan.energy.global.MyApplication;
import com.qifan.energy.mvp.callback.ICallBack;
import com.qifan.energy.bean.result.OSSPolicyResult;
import com.qifan.energy.util.SharedPreferencesUtil;
import com.orhanobut.logger.Logger;

/**
 * 网络OSS上传帮助类
 */
public class OSSNetUtils {
    public static final String TAG = "OSSNetUtils";
    private OSSNetUtils(){
        //首次初始化
        initOSS();
    }
    /**
     * "domain":"oss-cn-hangzhou.aliyuncs.com",
     * "bucket":"tbc-nodefile",
     * "accessKeyId":"",
     * "accessKeySecret":"",
     * "securityToken":""
     */
    private static OSSNetUtils ossNetUtils;

    public static OSSNetUtils getInstance() {
        if (ossNetUtils == null) {
            synchronized (OSSNetUtils.class) {
                if (ossNetUtils == null) {
                    ossNetUtils = new OSSNetUtils();
                }
            }
        }
        return ossNetUtils;
    }

    private OSSClient mOSS;

    public OSSPolicyResult getPolicyResult() {
        return  (OSSPolicyResult)SharedPreferencesUtil.getData(Keys.OSS_TOKEN_KEY,new OSSPolicyResult());
    }

    /* init初始化 */
    private void initOSS() {

        //调用此方法即可开启日志
        OSSLog.enableLog();

        String endpoint = "http://" + getPolicyResult().getDomain();
        // 在移动端建议使用STS的方式初始化OSSClient。
        OSSCredentialProvider credentialProvider = new OSSStsTokenCredentialProvider(getPolicyResult().getAccessKeyId()
                , getPolicyResult().getPolicy(), getPolicyResult().getSignature());
        ClientConfiguration conf = new ClientConfiguration();
        //conf.setHttpDnsEnable(true);//默认为true 表开启，需要关闭可以设置为false。
        conf.setConnectionTimeout(15 * 1000); // 连接超时，默认15秒。
        conf.setSocketTimeout(15 * 1000); // socket超时，默认15秒。
        conf.setMaxConcurrentRequest(5); // 最大并发请求书，默认5个。
        conf.setMaxErrorRetry(2); // 失败后最大重试次数，默认2次。
        mOSS = new OSSClient(MyApplication.getContext(), endpoint, credentialProvider, conf);
    }

    /* 上传文件 */
    public void asyncUploadFile(String objName, ICallBack<String> callBack){

        // 构造上传请求。
        PutObjectRequest put = new PutObjectRequest(getPolicyResult().getBucketName(), objName, getPolicyResult().getDir());

        // 异步上传时可以设置进度回调。
        put.setProgressCallback(new OSSProgressCallback<PutObjectRequest>() {
            @Override
            public void onProgress(PutObjectRequest request, long currentSize, long totalSize) {
                Logger.d("PutObject", "currentSize: " + currentSize + " totalSize: " + totalSize);
            }
        });

        OSSAsyncTask task = mOSS.asyncPutObject(put, new OSSCompletedCallback<PutObjectRequest, PutObjectResult>() {
            @Override
            public void onSuccess(PutObjectRequest request, PutObjectResult result) {
                Logger.d("PutObject", "UploadSuccess");
                Logger.d("ETag", result.getETag());
                Logger.d("RequestId", result.getRequestId());
                if (callBack != null) callBack.onSuccess(result.getRequestId());
            }

            @Override
            public void onFailure(PutObjectRequest request, ClientException clientExcepion, ServiceException serviceException) {
                // 请求异常。
                if (clientExcepion != null) {
                    // 本地异常，如网络异常等。
                    clientExcepion.printStackTrace();
                }
                if (serviceException != null) {
                    // 服务异常。
                    Logger.e("ErrorCode", serviceException.getErrorCode());
                    Logger.e("RequestId", serviceException.getRequestId());
                    Logger.e("HostId", serviceException.getHostId());
                    Logger.e("RawMessage", serviceException.getRawMessage());
                }
                if (callBack != null) callBack.onFailed(serviceException.getRawMessage());
            }
        });
        // task.cancel(); // 可以取消任务。
        // task.waitUntilFinished(); // 等待上传完成。
    }
}
